package org.zch.common.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

/**
 * Http请求工具类
 *
 * @Author 刘新
 * @Date 2024/1/15 14:23
 */
public class HttpUtils {

    /**
     * RestTemplate 发送get请求
     * @param url 请求url
     * @return
     */
    public String doGet(String url){
        RestTemplate restTemplate = new RestTemplate();
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        headers.set("Authorization", "Bearer your_access_token");
        // 创建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(headers);
        // 发送GET请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        // 处理响应
        String responseBody = "";
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            responseBody = responseEntity.getBody().replace("\n", "");
            System.out.println("请求成功，响应数据：" + responseBody);
        } else {
            System.out.println("请求失败，状态码：" + responseEntity.getStatusCode());
        }
        return  responseBody;
    }

}
